<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ProductMenu
 *
 * @author NGOC SANG
 */
class ProductMenu extends CWidget {
    //put your code here
    //
    public function init()
    {
        $cs = Yii::app()->getClientScript();
                
        $cs->registerCssFile(Yii::app()->theme->baseUrl."/css/vertical_menu.css");
        $cs->registerScriptFile(Yii::app()->theme->baseUrl."/js/vertical_menu.js");
        parent::init();
    }

    public function run() {   
        
        $treeData=ProductCategory::getTreeData();      
        $this->widget('CTreeView', array(
        'id'=>'category-tree',
        'data'=>$treeData['nodes'],
        'animated'=>'normal',
        'collapsed'=>true,
        'htmlOptions'=>array(
        'class'=>'vertical_menu'
        )));
       
    }       
    public function getTreeData($appendNodeId=null, $level=0, $begin=0, $categories=null){
        if(!$categories)
            $categories = ProductCategory::model()->findAll(array('order' => 'root,lft'));                
        $parentNeedAppand=false;
        $results=array();        
        $i=$begin;
        $total=count($categories);
        while($i<$total){
            $category=$categories[$i];
            if($category->level>=$level){
                $level=$category->level;
                $r=array();
                $r['text']=$category->name;
                $r['id']='node_'.$category->id;
                $r['hasChildren']=false;
                if($parentNeedAppand===false && $category->id==$appendNodeId){
                    $parentNeedAppand=true;
                }
                if(isset($categories[$i+1]) && $categories[$i+1]->level>$level){
                    $r['hasChildren']=true;
                    $ret=$this->getTreeData($appendNodeId, $level, $i+1, $categories);
                    $r['children']=$ret['nodes'];
                    if($parentNeedAppand===false && $ret['parentNeedAppand']===true){
                        $parentNeedAppand=true;
                    }
                    
                    if($ret['parentNeedAppand']){
                        $r['expanded']=true;
                    }
                    
                    $i=$ret['index'];
                }

                $results[]=$r;
            }else if($category->level<$level){
                return array(
                    'nodes'=>$results,
                    'parentNeedAppand'=>$parentNeedAppand,
                    'index'=>$i-1
                );
            }
            
            $i++;
        }
        
        return array(
            'nodes'=>$results,
            'index'=>$i
        );
                
    }    
    
      

}
